package com.lzy.business.facade;

import com.github.pagehelper.PageInfo;
import com.lzy.base.service.SysUserAdminService;
import com.lzy.business.response.CouponProfitRecordResponse;
import com.lzy.common.apis.SmsSendServiceApi;
import com.lzy.common.dtos.SmsSendDto;
import com.lzy.framework.core.datasource.multiple.DataSource;
import com.lzy.framework.core.datasource.multiple.DataSourceHolder;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.utils.DateUtil;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.member.apis.MemberUserServiceApi;
import com.lzy.member.dtos.MemberUserDto;
import com.lzy.payment.apis.PayBillApi;
import com.lzy.payment.apis.PayMemberAccountApi;
import com.lzy.payment.constants.CommonConstants;
import com.lzy.payment.dtos.memberAccount.LzNumberDTO;
import com.lzy.payment.dtos.pay.MemberAccountQueryParamDTO;
import com.lzy.payment.dtos.payBill.PayBillDTO;
import com.lzy.payment.service.PayMemberAccountService;
import com.lzy.product.apis.CouponProfitRecordServiceApi;
import com.lzy.product.apis.MemberCouponsServiceApi;
import com.lzy.product.common.util.EnumUtil;
import com.lzy.product.constants.BusinessType;
import com.lzy.product.dtos.CouponProfitRecordDto;
import com.lzy.product.dtos.MemberCouponsDto;
import com.lzy.sms.apis.UMengApi;
import com.lzy.sms.constants.BusiTypeEnum;
import com.lzy.sms.entity.UMengParam;
import com.lzy.sms.youMeng.base.AndroidNotification;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 卡券宝收益记录
 * Created by WIN7 on 2018/1/11.
 */
@Component
public class CouponProfitRecordFacade {
    public static final Logger LOGGER = LoggerFactory.getLogger(CouponProfitRecordFacade.class);
    @Autowired
    private CouponProfitRecordServiceApi couponProfitRecordServiceApi;
    @Autowired
    private MemberUserServiceApi memberUserServiceApi;
    @Autowired
    private MemberCouponsServiceApi memberCouponsServiceApi;
    @Autowired
    private PayMemberAccountApi payMemberAccountApi;
    @Autowired
    private SysUserAdminService sysUserAdminService;
    @Autowired
    private PayBillApi payBillApi;
    @Autowired
    private PayMemberAccountService payMemberAccountService;
    @Autowired
    private SmsSendServiceApi smsSendServiceApi;

    @Autowired
    private UMengApi uMengApi;

    //通知声音
    private final static String SOUND = "unbelievable";
    //包名
    private final static String ACTIVITY = "com.lzhy.moneyhll.activity.me.myWallet.MyWalletActivity";

    @Value("${uMeng.Debug}")
    private Boolean uMenngDebug;

    public PageInfo<CouponProfitRecordResponse> couponProfitList(Pager pager, CouponProfitRecordDto paramDto) {
        PageInfo pageInfo = couponProfitRecordServiceApi.selectList(pager, paramDto);

        if (pageInfo != null && pageInfo.getList() != null && pageInfo.getList().size() > 0) {
            List<CouponProfitRecordResponse> list = DozerUtils.maps(pageInfo.getList(), CouponProfitRecordResponse.class);
            DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
            for (CouponProfitRecordResponse response : list) {
                MemberUserDto memberUserDto = memberUserServiceApi.findById(Long.parseLong(response.getMemberId()));
                if (memberUserDto != null) {
                    response.setMemberPhone(memberUserDto.getAccount());
                }
                response.setStatusStr(EnumUtil.valueOf(BusinessType.CouponProfitStatus.class, response.getStatus()).getDesc());
            }

            DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
            pageInfo.setList(list);
            return pageInfo;
        }

        return null;
    }

    public Boolean updateProfitRecordsStatus(List<CouponProfitRecordDto> recordDtoList, Integer status) {
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_PRODUCT);
        //需要更新的状态
        Integer updateStatus = status;

        //更新卡券宝金额
        for (CouponProfitRecordDto recordDto : recordDtoList) {
            //是否为可提现金额
            Boolean flag = false;
            //收益记录更新状态
            CouponProfitRecordDto updateDto = new CouponProfitRecordDto();
            updateDto.setId(recordDto.getId());

            if (recordDto.getMemberId() != null) {
                try {
                    MemberCouponsDto memberCouponsDto = new MemberCouponsDto();
                    memberCouponsDto.setMemberId(recordDto.getMemberId());
                    memberCouponsDto.setOrderId(recordDto.getOrderId());
                    if (BusinessType.CouponProfitStatus.LIMITED.getCode().equals(status)) {//1-可限制
                        memberCouponsDto.setLimitedMoney(recordDto.getAmount());
                    } else {//3-可提现
                        memberCouponsDto.setAvailableMoney(recordDto.getAmount());//可提现增加
                        memberCouponsDto.setLimitedMoney(recordDto.getAmount().multiply(new BigDecimal(-1)));//冻结金额相应减少
                        flag = true;
                    }

                    //判断是否更新成功，更新收益记录状态（1-已限制 2-限制错误 3-可提现 4-可提现错误）
                    if (memberCouponsServiceApi.updateMemberCoupons(memberCouponsDto)) {
                        updateDto.setStatus(status);
                    } else {
                        flag = false;
                        //更新失败
                        updateDto.setStatus(status + 1);
                        updateStatus = status + 1;
                    }
                } catch (Exception e) {
                    flag = false;
                    //更新失败
                    updateDto.setStatus(status + 1);
                    updateStatus = status + 1;
                    LOGGER.error("更新卡券宝" + EnumUtil.valueOf(BusinessType.CouponProfitStatus.class, status).getDesc() + "金额失败！收益记录ID(CouponProfitRecordDto):" + recordDto.getId());
                }

                if (flag) {
                    //如果金额，大于0
                    if (recordDto.getAmount() != null && recordDto.getAmount().compareTo(new BigDecimal(0)) > 0) {
                        DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);

                        //更新账户提现金额
                        MemberUserDto memberUser = memberUserServiceApi.selectMemberById(recordDto.getMemberId());
                        LzNumberDTO lbNumberDTO = new LzNumberDTO();
                        if (recordDto.getType() == 2) {//佣金
                            Ensure.that(memberUser).isNotNull("08000002");
                            MemberAccountQueryParamDTO maqpDto = new MemberAccountQueryParamDTO();
                            maqpDto.setAmount(recordDto.getAmount());
                            maqpDto.setUserId(memberUser.getId());
                            payMemberAccountApi.updateCommissionLBAdd(maqpDto);//更新龙币到2.1（佣金）
                        } else {//可提现
                            Ensure.that(memberUser).isNotNull("08000002");
                            lbNumberDTO.setUserId(recordDto.getMemberId());
                            lbNumberDTO.setMobile(memberUser.getAccount());
                            lbNumberDTO.setAddNumber(recordDto.getAmount());
                            payMemberAccountApi.updateNumberLBAdd(lbNumberDTO);//更新龙币到2.1（可提现）
                        }

                        PayBillDTO payBillDTO = new PayBillDTO();
                        payBillDTO.setUserId(memberUser.getId());
                        payBillDTO.setSerialId(recordDto.getId());
                        payBillDTO.setAmount(recordDto.getAmount());
                        payBillDTO.setRole(CommonConstants.PayMemberAccountRole.shop.getIndex());
                        payBillDTO.setCorrectFlag(CommonConstants.CorrectFlag.CORRECT_FLAG.getIndex());
                        if (recordDto.getType() == null) {
                            recordDto.setType(1);
                        }
                        if (recordDto.getType().equals(1)) {//套餐补贴
                            payBillDTO.setType(CommonConstants.BillType.profit.getIndex());
                            payBillDTO.setDemo("套餐补贴");
                        }
                        if (recordDto.getType().equals(2)) {//佣金
                            payBillDTO.setType(CommonConstants.BillType.commission.getIndex());
                            payBillDTO.setDemo("佣金");
                        }
                        if (recordDto.getType().equals(3)) {//卖券收益
                            payBillDTO.setType(CommonConstants.BillType.coupons.getIndex());
                            payBillDTO.setDemo("卖券收益");
                        }
                        payBillApi.createPayBill(payBillDTO);

                        if (recordDto.getType().equals(1)) {
                            //将要发送短信的基本信息加进临时表tmp_sms_send
                            SmsSendDto smsSendDto = new SmsSendDto();
                            smsSendDto.setPhone(memberUser.getAccount());
                            smsSendDto.setBusiType(BusiTypeEnum.PRODUCT_PROMOTE_SUBSIDY.getVal());
                            //封装短信参数，以"|"分隔
                            String param = "";
                            String time = DateUtil.getCurrentDate() + " 1:00";
                            BigDecimal amount = new BigDecimal(0);
                            //获取龙币余额
                            if (lbNumberDTO.getMobile() != null && !"".equals(lbNumberDTO.getMobile())) {
                                MemberUserDto memberUserDto = memberUserServiceApi.findMemberByMobile(lbNumberDTO.getMobile());
                                if (memberUserDto != null) {
                                    amount = payMemberAccountService.queryLbBalance(memberUserDto.getId());
                                }
                            }
                            if (amount != null) {
                                param = recordDto.getAmount() + "|" + time + "|" + amount;
                            }
                            smsSendDto.setNumber(param);
                            smsSendDto.setType(1);
                            smsSendServiceApi.addSmsSend(smsSendDto);
                        }
                    }
                }

                DataSourceHolder.clearDataSource();
                couponProfitRecordServiceApi.update(updateDto);
            }
        }
        return updateStatus % 2 != 0;
    }

    public Integer sendPromote() {
        DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
        //从数据里面拿出要发送的推送参数
        SmsSendDto smsSendDto = new SmsSendDto();
        smsSendDto.setBusiType(BusiTypeEnum.PRODUCT_PROMOTE_SUBSIDY.getVal());
        smsSendDto.setStatus(BusinessType.SendStatus.UNSENT.getCode());
        smsSendDto.setType(1);
        List<SmsSendDto> smsSendDtoList = smsSendServiceApi.selectSmsSend(smsSendDto);
        Integer m = 0;
        SmsSendDto smsSendDto1 = new SmsSendDto();
        for (SmsSendDto dto : smsSendDtoList) {
            //解析参数
            String param = dto.getNumber();
            String[] paramStr = param.split("\\|");
            if (paramStr != null && paramStr.length > 2) {
                //更新状态
                MemberUserDto memberUserDto = memberUserServiceApi.findMemberByMobile(dto.getPhone());
                if (null != memberUserDto && memberUserDto.getDeviceType() != null && null != memberUserDto.getDeviceToken()) {
                    UMengParam uMengParam = new UMengParam();
                    uMengParam.setProductionMode(!uMenngDebug);
                    uMengParam.setActivity(ACTIVITY);
                    uMengParam.setAfterOpen(AndroidNotification.AfterOpenAction.go_activity.toString());
                    uMengParam.setDeviceToken(memberUserDto.getDeviceToken());
                    uMengParam.setDeviceType(memberUserDto.getDeviceType());
                    uMengParam.setText("您的钱包有" + paramStr[0] + "元到账了，账户余额为" + paramStr[2] + "元。请注意查收！");
                    uMengParam.setTitle("龙之游消息");
                    uMengParam.setTicker("您的钱包有" + paramStr[0] + "元到账了，账户余额为" + paramStr[2] + "元。请注意查收！");
                    uMengParam.setSound(SOUND);
                    if (memberUserDto.getDeviceType().equals(2)) {
                        uMengParam.setSound(uMengParam.getSound() + ".caf");
                    }
                    uMengParam.setDisplayType(AndroidNotification.DisplayType.NOTIFICATION.getValue());
                    JSONObject result = uMengApi.unicast(uMengParam);
                    //发送成功
                    if (result.getString("ret").equals("SUCCESS")) {
                        smsSendDto1.setPhone(dto.getPhone());
                        smsSendDto1.setStatus(BusinessType.SendStatus.SEND.getCode());
                        smsSendDto1.setId(dto.getId());
                        smsSendServiceApi.updateSmsSend(smsSendDto1);
                        m++;
                    }
                }
            }
        }
        DataSourceHolder.clearDataSource();
        return m;
    }
}
